package com.yjc.springcloud.controller;

import com.yjc.springcloud.bean.CommotResult;
import com.yjc.springcloud.bean.Payment;
import com.yjc.springcloud.lb.LoadBalancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author shkstart
 * @create 2022-07-12 22:35
 */
@RestController
public class OrderController {

    private final static String FINAL_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    LoadBalancer loadBalancer;

    @GetMapping("/consumer/add/payment")
    public CommotResult addPayment(Payment payment) {
        return restTemplate.postForObject(FINAL_URL + "/add/payment", payment, CommotResult.class);
    }

    @GetMapping("/consumer/addEntity/payment")
    public CommotResult addPaymentEntity(Payment payment) {
        ResponseEntity<CommotResult> res = restTemplate.postForEntity(FINAL_URL + "/add/payment", payment, CommotResult.class);
        return res.getBody();
    }

    @GetMapping("/consumer/get/payment/{id}")
    public CommotResult getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(FINAL_URL + "/get/payment/" + id, CommotResult.class);
    }

    @GetMapping("/consumer/getEntity/payment/{id}")
    public CommotResult getPaymentEntity(@PathVariable("id") Long id) {
        return restTemplate.getForEntity(FINAL_URL + "/get/payment/" + id, CommotResult.class).getBody();
    }

    //手写负载均衡的轮询规则
    @GetMapping("/consumer/payment/lb")
    public String lb() {
        //0
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        //1
        ServiceInstance res = loadBalancer.getServiceInstance(instances);
        if (instances == null) {
            return null;
        }
        //2
        return restTemplate.getForObject(res.getUri() + "/payment/lb", String.class);
    }


}
